<template>
    <div class="layout-padding">
        <el-form :inline="true" ref="queryRef" :model="queryParams" label-width="120px">
            <el-row>
                <el-col :span="24">
                    <el-form-item label="区段：">
                        <el-tree-select v-model="queryParams.section" :data="dataSource" clearable
                            :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
                            :render-after-expand="false" check-strictly @change="treeChange">
                        </el-tree-select>
                    </el-form-item>
                    <el-form-item label="工区：">
                        <el-tree-select v-model="queryParams.workArea" :data="dataSourceArea" clearable
                            :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
                            :render-after-expand="false" check-strictly>
                        </el-tree-select>
                    </el-form-item>
                    <el-form-item label="日期：">
                        <el-date-picker v-model="queryParams.time" type="datetimerange" range-separator="—"
                            start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss"
                            format="YYYY-MM-DD HH:mm:ss" @change="calendarChange" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="冻害类型：">
                        <el-radio-group v-model="queryParams.freezeType">
                            <el-radio label="10mm以上"></el-radio>
                            <el-radio label="10mm以下"></el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
                        <el-button type="primary" @click="handleExport">导出</el-button>
                        <el-button type="primary" @click="handleImport">导入</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <el-table v-loading="loading" :data="list">
            <el-table-column type="index" width="50" label="序号"></el-table-column>
            <el-table-column label="类型" align="center" prop="freezeType" />
            <el-table-column label="区段" align="center" prop="sectionName" />
            <el-table-column label="工区" align="center" prop="workAreaName" />
            <el-table-column label="日期" align="center" prop="freezeTime" />
            <el-table-column label="里程" align="center">
                <template #default="scope">
                    {{ `${scope.row.xingType??''}` }}{{transformToOriginalFormat(scope.row.kilometer)}}{{ !!scope.row.remark ?`(${scope.row.remark??''})`:'' }}
                </template>
            </el-table-column>
            <el-table-column label="长度" align="center" prop="length" />
            <el-table-column label="高度-左股" align="center" prop="heigthLeft" />
            <el-table-column label="高度-右股" align="center" prop="heigthRight" />
            <el-table-column label="曲/直线" align="center" prop="lineType" />

            <el-table-column label="修复情况" width="180" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" icon="Edit"
                        @click="handleFreezeRestoreView(scope.row)">查看</el-button>
                </template>
            </el-table-column>
            <el-table-column label="回落情况" width="180" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" icon="Edit"
                        @click="handLefreezeFallbackView(scope.row)">查看</el-button>
                </template>
            </el-table-column>
            <el-table-column label="TQI（200m范围内）" align="center" prop="tqi" />
            <el-table-column label="操作" align="center">
                <template #default="scope">
                    <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:config:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />

        <!-- 恢复情况详情对话框 -->
        <el-dialog title="恢复情况" v-model="freezeRestoreOpen" width="900px" append-to-body>
            <el-table v-loading="loading" :data="freezeRestoreList">
                <el-table-column type="index" width="50" label="序号"></el-table-column>
                <el-table-column label="日期" align="center" prop="restoreTime" />
                <el-table-column label="里程" align="center" prop="mileage" />
                <el-table-column label="长度" align="center" prop="length" />
            </el-table>
        </el-dialog>

        <!-- 回落情况详情对话框 -->
        <el-dialog title="回落情况" v-model="freezeFallbackOpen" width="900px" append-to-body>
            <el-table v-loading="loading" :data="freezeFallbackList">
                <el-table-column type="index" width="50" label="序号"></el-table-column>
                <el-table-column label="日期" align="center" prop="fallbackTime" />
                <el-table-column label="长度" align="center">
                    <el-table-column label="回落(m)" align="center" prop="fallbackLength" />
                    <el-table-column label="还有(m)" align="center" prop="stillLength" />
                </el-table-column>

                <el-table-column label="高度" align="center">
                    <el-table-column label="回落(m)" align="center">
                        <el-table-column label="左股" align="center" prop="fallbackHeightLeft" />
                        <el-table-column label="右股" align="center" prop="fallbackHeightRight" />
                    </el-table-column>
                    <el-table-column label="还有(m)" align="center">
                        <el-table-column label="左股" align="center" prop="stillHeightLeft" />
                        <el-table-column label="右股" align="center" prop="stillHeightRight" />
                    </el-table-column>
                </el-table-column>
                <el-table-column label="整修长度(m)" align="center" prop="repairLength" />
            </el-table>
        </el-dialog>


        <!-- 附图 -->
        <el-dialog v-model="dialogVisible" title="预览" width="800px" append-to-body>
            <span>整改前：</span>
            <div v-for="item in beforeImageUrlList" :key="item" style="margin-bottom: 10px;">
                <img :src="item" style="display: block; max-width: 100%; margin: 0 auto" />
            </div>
            <span>整改后：</span>
            <div v-for="item in afterUrlImageUrlList" :key="item" style="margin-bottom: 10px;">
                <img :src="item" style="display: block; max-width: 100%; margin: 0 auto" />
            </div>
        </el-dialog>



        <!-- 导入对话框 -->
        <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
            <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                    <div class="el-upload__tip text-center">
                        <div class="el-upload__tip"><el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据</div>
                        <span>仅允许导入xls、xlsx格式文件。</span>
                        <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
                            @click="importTemplate">下载模板</el-link>
                    </div>
                </template>
            </el-upload>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitFileForm">确 定</el-button>
                    <el-button @click="upload.open = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>

<script setup>
import { listFreeze, exportFreeze, getFreezeRestore, getFreezeFallback } from "@/api/system/injury.js";
import { getTreeList, getDeptBy,delfreeze } from "@/api/work";
import { getToken } from '@/utils/auth'
const { proxy } = getCurrentInstance();

const data = reactive({
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        sectionName: undefined,
        workAreaName: undefined,
        freezeType: undefined,
        time: [],
        params: {
            startTime: undefined,
            endTime: undefined,
        }
    }
});

function transformToOriginalFormat(inputString) {
    if (inputString === undefined || inputString === null || inputString === '') {
        return '';
    }
    
    const parts = inputString.split(',');
    const firstPart = 'K' + parts[0] || 0;
    const secondPart = parts[1] || 0;
    const thirdPart = 'K' + parts[2] || 0;
    const fourthPart = parts[3] || 0;
    return `${firstPart}+${secondPart}-${thirdPart}+${fourthPart}`;
}

const { queryParams } = toRefs(data);

const loading = ref(true);
const list = ref([]);
const freezeRestoreList = ref([]);
const freezeFallbackList = ref([]);
const total = ref(0);
const freezeRestoreOpen = ref(false);
const freezeFallbackOpen = ref(false);
const dialogVisible = ref(false);
const beforeImageUrlList = ref([]);
const afterUrlImageUrlList = ref([]);


/*** 用户导入参数 */
const upload = reactive({
    // 是否显示弹出层
    open: false,
    // 弹出层标题
    title: '',
    // 是否禁用上传
    isUploading: false,
    // 是否更新已经存在的用户数据
    updateSupport: 0,
    // 设置上传的请求头部
    headers: { Authorization: 'Bearer ' + getToken() },
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + '/sjgtw-emergency/freeze/importData',
})

//区段数据
const dataSource = ref([])
const dataSourceArea = ref([])
function getTree() {
    getTreeList().then(res => {
        dataSource.value = res.data
    })
}
getTree()

function treeChange(id) {
    queryParams.value.workArea = ''
    dataSourceArea.value = []
    if(id == null || id == undefined || id == ''){
        return
    }
    getDeptBy({
        parentId: id
    }).then(res => {
        dataSourceArea.value = res.data
    })
}

/** 查询公告列表 */
function getList() {
    loading.value = true;
    listFreeze(queryParams.value).then(response => {
        list.value = response.rows;
        total.value = response.total;
        loading.value = false;
    });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const configIds = row.id
  proxy.$modal.confirm('是否确认删除idid为"' + configIds + '"的数据项？').then(function () {
    return delfreeze(configIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}
/** 搜索按钮操作 */
function handleQuery() {
    if (queryParams.value.time !== null && queryParams.value.time.length > 1) {
        queryParams.value.params.startTime = queryParams.value.time[0];
        queryParams.value.params.endTime = queryParams.value.time[1];
    }
    queryParams.value.pageNum = 1;
    getList();
}

//  恢复情况查看
function handleFreezeRestoreView(row) {
    freezeRestoreOpen.value = true;
    getFreezeRestore({
        freezeId: row.id
    }).then(res => {
        freezeRestoreList.value = res.rows
    })
}
//  回落情况查看
function handLefreezeFallbackView(row) {
    freezeFallbackOpen.value = true;
    getFreezeFallback({
        freezeId: row.id
    }).then(res => {
        freezeFallbackList.value = res.rows
    })
}

function calendarChange(value) {
    if (value == null) {
        queryParams.value.params.startTime = undefined;
        queryParams.value.params.endTime = undefined;
    }
}


/** 导出按钮操作 */
function handleExport() {
    proxy.download("sjgtw-emergency/freeze/export", {
        ...queryParams.value
    }, `冻害记录${new Date().getTime()}.xlsx`);
}


/** 导入按钮操作 */
function handleImport() {
    upload.title = '导入'
    upload.open = true
}

/** 提交上传文件 */
function submitFileForm() {
    proxy.$refs['uploadRef'].submit()
}

/** 下载模板操作 */
function importTemplate() {
    proxy.download('sjgtw-emergency/freeze/downloadTemplate', {}, `template_${new Date().getTime()}.xlsx`)
}

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
    upload.open = false
    upload.isUploading = false
    proxy.$refs['uploadRef'].handleRemove(file)
    if (response.code == 200) {
        proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
    } else {
        proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.data + '</div>', '导入失败', { dangerouslyUseHTMLString: true })
    }
    getList()
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
    upload.isUploading = true
}

getList();
</script>

<style lang="scss" scoped>
.layout-padding {
    padding: 10px;
}
</style>